const QuoteApi = require('../../../api/quote.js');
const util = require('../../../utils/util');
const commonUtil = require('../../../utils/common.js')
const {metalList, metalList_daily, metalList_weekly} = require('../../utils/metalList.js');
const {LMEStockColumns, LMECancelledColumns, COMEXColumns, SHFEDailyColumn, SHFEWeeklyColumn, SHFETradingMarketColumn} = require('../../../utils/data.js');

Page({
  data: {
    currentNav: 0,
    currentShfeNav: 'cu',
    pageList: [
      {itemId: 0, itemName: 'LME基本金属开盘库存'},
      {itemId: 1, itemName: 'LME基本金属注销仓单'},
      {itemId: 2, itemName: 'COMEX铜库存'},
      {itemId: 3, itemName: '上期所仓单日报'},
      {itemId: 4, itemName: '上期所库存周报'},
      {itemId: 5, itemName: '上期所期货交易行情'},
    ],
    shfeNavList: [
      {itemId: 'cu', itemName: '铜'},
      {itemId: 'al', itemName: '铝'},
      {itemId: 'zn', itemName: '锌'},
      {itemId: 'pb', itemName: '铅'},
      {itemId: 'ni', itemName: '镍'},
      {itemId: 'sn', itemName: '锡'},
    ],
    tradeDate: null,
    title: null,
    unit: null,
    tableInfo: {
      columns: [],
      data: [],
      inData: true,
    },
    shfeTableData: [],
    columnsArray: [LMEStockColumns, LMECancelledColumns, COMEXColumns, SHFEDailyColumn, SHFEWeeklyColumn, SHFETradingMarketColumn]
  },

  onLoad(options) {
    console.log(options);
    if (options.isShare) {
      let _tradeDate = options.tradeDate == 'null' ? null : options.tradeDate;
      this.setData({
        currentNav: options.currentNav,
        currentShfeNav: options.currentShfeNav,
        tradeDate: _tradeDate,
        ['tableInfo.columns']: this.data.columnsArray[options.currentNav],
        ['tableInfo.data']: [],
        unit: null,
        title: null
      })
      console.log(options.currentNav);
      if (options.currentNav == "0") {
        this.getLmeStockFrontList()
      } else if (options.currentNav == "1") {
        this.getLmeWarehouseFrontList();
      } else if (options.currentNav == "2") {
        this.getComexFrontList();
      } else if (options.currentNav == "3") {
        this.getShfeWarehouseFrontList();
      } else if (options.currentNav == "4") {
        this.getShfeStockFrontList();
      } else if (options.currentNav == "5") {
        this.getShfeFuturesQuotesList();
      }
    } else {
      this.setData({
        currentNav: 0,
        tradeDate: null,
        ['tableInfo.columns']: this.data.columnsArray[0]
      })
      this.getLmeStockFrontList()
    }
  },

  onShow() {
    console.log('onshow');
  },
  onHide(){
    console.log('hide');
    console.log(this.data.tradeDate);
  },
  onUnload(){
    console.log('onunload');
  },
  // COMEX铜库存
  getComexFrontList(){
    let _tradeDate = this.data.tradeDate != null ? util.formatDate(this.data.tradeDate, 'YY-MM-DD') : '';
    QuoteApi.getComexFrontList({tradeDate: _tradeDate}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        if (res.data.length > 0) {
          let array = res.data.map(item=>{
            item.metalType = 'cu';
            item.metalTypeName = '铜';
            item.changeStockQuantity_th = util.Thousandth(item.changeStockQuantity);
            item.registerStockQuantity_th = util.Thousandth(item.registerStockQuantity);
            return item;
          });
          if (!this.data.tradeDate) {
            let _title = util.formatDate(array[0].tradeDate, 'M月D日') + ' COMEX铜库存统计';
            let arr = [];
            array.forEach(item=>{
              item.changeStockQuantity_th = util.Thousandth(item.changeStockQuantity);
              item.registerStockQuantity_th = util.Thousandth(item.registerStockQuantity);

              if (item.tradeDate == array[0].tradeDate) {
                arr.push(item);
              }
            })
            this.setData({
              unit: '单位：短吨',
              title: _title,
              ['tableInfo.data']: arr
            })
          } else {
            console.log(array);
            this.setData({
              ['tableInfo.data']: array
            })
          }
        } else {
          this.setData({
            unit: '单位：短吨',
            title: 'COMEX铜库存统计',
            ['tableInfo.data']: []
          })
        }
      } else {
        if (res.errCode == '999901') {
          commonUtil.handleTokenExpire('/packageA/pages/data/index', 'link')
        }
      }
    })
  },
  // LME基本金属注销仓单
  getLmeWarehouseFrontList(){
    let _tradeDate = this.data.tradeDate != null ? util.formatDate(this.data.tradeDate, 'YY-MM-DD') : '';
    QuoteApi.getLmeWarehouseFrontList({tradeDate: _tradeDate}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        if (res.data.length>0) {
          let arr = [];
          let sortArr = metalList;
          if (!this.data.tradeDate) {
            let _title = util.formatDate(res.data[0].tradeDate, 'M月D日') + ' LME基本金属注销仓单';
            res.data.forEach(item=>{
              if (item.tradeDate == res.data[0].tradeDate) {
                arr.push(item)
              }
            })
            this.setData({
              unit: '单位：吨',
              title: _title
            })
          }
          let searchArr = !this.data.tradeDate ? arr : res.data;
          let emptyObj = {changeRate: null, changeStockQuantity: null, changeStockRate: null, previousDayChangeRate: null, registerStockQuantity: null, registerStockRate: null, totalStockQuantity: null};
          let emptyKeys = Object.keys(emptyObj);
          sortArr.forEach(item => {
            emptyKeys.forEach(s=>{
                item[s] = emptyObj[s];
            })

            let obj = searchArr.find(i => i.metalType == item.metalType);
            if (obj) {
                item.metalTypeName = util.metalNameFilter(obj.metalType);
                item.changeRate = obj.changeRate;
                item.changeStockQuantity = obj.changeStockQuantity;
                item.changeStockQuantity_th = util.Thousandth(obj.changeStockQuantity);
                item.changeStockRate = obj.changeStockRate;
                item.previousDayChangeRate = obj.previousDayChangeRate;
                item.registerStockQuantity = obj.registerStockQuantity;
                item.registerStockQuantity_th = util.Thousandth(obj.registerStockQuantity);
                item.registerStockRate = obj.registerStockRate;
                item.totalStockQuantity = obj.totalStockQuantity;
                item.totalStockQuantity_th = util.Thousandth(obj.totalStockQuantity);
            }
          })
          this.setData({
            ['tableInfo.data']: sortArr
          })
        } else {
          this.setData({
            unit: '单位：吨',
            title: 'LME基本金属注销仓单',
            ['tableInfo.data']: []
          })
        }
      } else {
        if (res.errCode == '999901') {
          commonUtil.handleTokenExpire('/packageA/pages/data/index', 'link')
        }
      }
    })
  },
  // LME基本金属库存报告
  getLmeStockFrontList(){
    let _tradeDate = this.data.tradeDate != null ? util.formatDate(this.data.tradeDate, 'YY-MM-DD') : '';
    QuoteApi.getLmeStockFrontList({tradeDate: _tradeDate}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        if (res.data.length>0) {
          let arr = [];
          let sortArr = metalList;
          if (!this.data.tradeDate) {
            let _title = util.formatDate(res.data[0].tradeDate, 'M月D日') + ' LME基本金属官方开盘库存报告';
            res.data.forEach(item=>{
              if (item.tradeDate == res.data[0].tradeDate) {
                arr.push(item)
              }
            })
            this.setData({
              unit: '单位：吨',
              title: _title
            })
          }
          let searchArr = !this.data.tradeDate ? arr : res.data;
          let emptyObj = { changeStockQuantity: null, previousDayStockQuantity: null, totalStockQuantity: null };
          let emptyKeys = Object.keys(emptyObj);
          sortArr.forEach(item => {
            emptyKeys.forEach(s=>{
              item[s] = emptyObj[s];
            })

            let obj = searchArr.find(i => i.metalType == item.metalType);
            if (obj) {
              item.metalTypeName = util.metalNameFilter(obj.metalType);
              item.changeStockQuantity = obj.changeStockQuantity;
              item.changeStockQuantity_th = util.Thousandth(obj.changeStockQuantity);
              item.previousDayStockQuantity = obj.previousDayStockQuantity;
              item.previousDayStockQuantity_th = util.Thousandth(obj.previousDayStockQuantity);
              item.totalStockQuantity = obj.totalStockQuantity;
              item.totalStockQuantity_th = util.Thousandth(obj.totalStockQuantity);
            }
          })
          console.log(sortArr);
          this.setData({
            ['tableInfo.data']: sortArr
          })
        } else {
          this.setData({
            unit: '单位：吨',
            title: 'LME基本金属官方开盘库存报告',
            ['tableInfo.data']: []
          })
        }
      } else {
        if (res.errCode == '999901') {
          commonUtil.handleTokenExpire('/packageA/pages/data/index', 'link')
        }
      }
    })
  },
  // 上期所仓单日报
  getShfeWarehouseFrontList(){
    let _tradeDate = this.data.tradeDate != null ? util.formatDate(this.data.tradeDate, 'YY-MM-DD') : '';
    QuoteApi.getShfeWarehouseFrontList({tradeDate: _tradeDate}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        if (res.data.length>0) {
          let arr = [];
          let sortArr = metalList_daily;
          if (!this.data.tradeDate) {
            let _title = util.formatDate(res.data[0].tradeDate, 'M月D日') + ' 上期所仓单日报';
            res.data.forEach(item=>{
              if (item.tradeDate == res.data[0].tradeDate) {
                arr.push(item)
              }
            })
            this.setData({
              unit: '单位：吨',
              title: _title
            })
          }
          let searchArr = !this.data.tradeDate ? arr : res.data;
          let emptyObj = { changeStockQuantity: null, previousDayStockQuantity: null, registerStockQuantity: null };
          let emptyKeys = Object.keys(emptyObj);
          sortArr.forEach(item => {
            emptyKeys.forEach(s=>{
              item[s] = emptyObj[s];
            })

            let obj = searchArr.find(i => i.metalType == item.metalType);
            if (obj) {
              item.metalTypeName = util.metalNameFilter(obj.metalType);
              item.changeStockQuantity = obj.changeStockQuantity;
              item.changeStockQuantity_th = util.Thousandth(obj.changeStockQuantity);
              item.previousDayStockQuantity = obj.previousDayStockQuantity;
              item.previousDayStockQuantity_th = util.Thousandth(obj.previousDayStockQuantity);
              item.registerStockQuantity = obj.registerStockQuantity;
              item.registerStockQuantity_th = util.Thousandth(obj.registerStockQuantity);
            }
          })
          this.setData({
            ['tableInfo.data']: sortArr
          })
        } else {
          this.setData({
            unit: '单位：吨',
            title: '上期所仓单日报',
            ['tableInfo.data']: []
          })
        }
      } else {
        if (res.errCode == '999901') {
          commonUtil.handleTokenExpire('/packageA/pages/data/index', 'link')
        }
      }
    })
  },
  // 上期所库存周报
  getShfeStockFrontList(){
    let _tradeDate = this.data.tradeDate != null ? util.formatDate(this.data.tradeDate, 'YY-MM-DD') : '';
    QuoteApi.getShfeStockFrontList({tradeDate: _tradeDate}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        if (res.data.length>0) {
          let arr = [];
          let sortArr = metalList_weekly;
          if (!this.data.tradeDate) {
            let _title = util.formatDate(res.data[0].tradeDate, 'M月D日') + ' 上期所库存周报';
            res.data.forEach(item=>{
              if (item.tradeDate == res.data[0].tradeDate) {
                arr.push(item)
              }
            })
            this.setData({
              unit: '单位：吨',
              title: _title
            })
          }
          let searchArr = !this.data.tradeDate ? arr : res.data;
          let emptyObj = { changeCapacityQuantity: null, changeFuturesQuantity: null, changeStockQuantity: null, lastCapacityQuantity: null,
            lastTotalFuturesQuantity: null, lastTotalStockQuantity: null, totalCapacityQuantity: null, totalFuturesQuantity: null, totalStockQuantity: null };
          let emptyKeys = Object.keys(emptyObj);
          sortArr.forEach(item => {
            emptyKeys.forEach(s=>{
              item[s] = emptyObj[s];
            })

            let obj = searchArr.find(i => i.metalType == item.metalType);
            if (obj) {
              item.metalTypeName = util.metalNameFilter(obj.metalType);
              item.changeCapacityQuantity = obj.changeCapacityQuantity;
              item.changeCapacityQuantity_th = util.Thousandth(obj.changeCapacityQuantity);
              item.changeFuturesQuantity = obj.changeFuturesQuantity;
              item.changeFuturesQuantity_th = util.Thousandth(obj.changeFuturesQuantity);
              item.changeStockQuantity = obj.changeStockQuantity;
              item.changeStockQuantity_th = util.Thousandth(obj.changeStockQuantity);
              item.lastCapacityQuantity = obj.lastCapacityQuantity;
              item.lastCapacityQuantity_th = util.Thousandth(obj.lastCapacityQuantity);
              item.lastTotalFuturesQuantity = obj.lastTotalFuturesQuantity;
              item.lastTotalFuturesQuantity_th = util.Thousandth(obj.lastTotalFuturesQuantity);
              item.lastTotalStockQuantity = obj.lastTotalStockQuantity;
              item.lastTotalStockQuantity_th = util.Thousandth(obj.lastTotalStockQuantity);
              item.totalCapacityQuantity = obj.totalCapacityQuantity;
              item.totalCapacityQuantity_th = util.Thousandth(obj.totalCapacityQuantity);
              item.totalFuturesQuantity = obj.totalFuturesQuantity;
              item.totalFuturesQuantity_th = util.Thousandth(obj.totalFuturesQuantity);
              item.totalStockQuantity = obj.totalStockQuantity;
              item.totalStockQuantity_th = util.Thousandth(obj.totalStockQuantity);
            }
          })
          this.setData({
            ['tableInfo.data']: sortArr
          })
        } else {
          this.setData({
            unit: '单位：吨',
            title: '上期所库存周报',
            ['tableInfo.data']: []
          })
        }
      } else {
        if (res.errCode == '999901') {
          commonUtil.handleTokenExpire('/packageA/pages/data/index', 'link')
        }
      }
    })
  },
  // 上期所交易行情
  getShfeFuturesQuotesList(){
    let _tradeDate = this.data.tradeDate != null ? util.formatDate(this.data.tradeDate, 'YY-MM-DD') : '';
    QuoteApi.getShfeFuturesQuotesList({tradeDate: _tradeDate}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        res.data.forEach(item=>{
          let _dealInterest = 0, _dealAmount = 0, _openInterest = 0, _changeInterest = 0;
          if (item.list && item.list.length > 0) {
            item.list.forEach((sub, sidx)=>{
              sub.metalType = item.metalType;
              sub.metalTypeName = util.metalNameFilter(item.metalType);
              _dealInterest += Number(sub.dealInterest);
              _dealAmount += Number(sub.dealAmount);
              _openInterest += Number(sub.openInterest);
              _changeInterest += Number(sub.changeInterest);
            })
            _dealInterest = String(_dealInterest).indexOf('.') > -1 ? util.bigNumberFixed(_dealInterest,2) : _dealInterest;
            _dealAmount = String(_dealAmount).indexOf('.') > -1 ? util.bigNumberFixed(_dealAmount,2) : _dealAmount;
            _openInterest = String(_openInterest).indexOf('.') > -1 ? util.bigNumberFixed(_openInterest,2) : _openInterest;
            _changeInterest = String(_changeInterest).indexOf('.') > -1 ? util.bigNumberFixed(_changeInterest,2) : _changeInterest;

            item.list.push({metalTypeName: '小计', metalType: '', dealInterest: _dealInterest, dealAmount: _dealAmount, openInterest: _openInterest, changeInterest: _changeInterest});
          }
        })
        this.setData({
          shfeTableData: res.data
        })

        let currentItem = res.data.filter(item=>item.metalType == this.data.currentShfeNav);
        let _title = currentItem.length > 0 ? util.formatDate(currentItem[0].tradeDate, 'M月D日') + ' 上期所期货交易行情' : '上期所期货交易行情';
        let _array = currentItem.length > 0 ? currentItem[0].list : [];

        this.setData({
          ['tableInfo.data']: _array,
          title: _title,
          unit: '',
        })
      } else {
        if (res.errCode == '999901') {
          commonUtil.handleTokenExpire('/packageA/pages/data/index', 'link')
        }
      }
    })
  },
  menuClick(e){
    let current = e.currentTarget.dataset.current;

    this.setData({
      currentNav: current,
      tradeDate: null,
      ['tableInfo.columns']: this.data.columnsArray[current],
      ['tableInfo.data']: [],
      unit: null,
      title: null
    })
    if (Number(current) == 0) {
      this.getLmeStockFrontList()
    } else if (Number(current) == 1) {
      this.getLmeWarehouseFrontList();
    } else if (Number(current) == 2) {
      this.getComexFrontList();
    } else if (Number(current) == 3) {
      this.getShfeWarehouseFrontList();
    } else if (Number(current) == 4) {
      this.getShfeStockFrontList();
    } else if (Number(current) == 5) {
      this.getShfeFuturesQuotesList();
    }
  },
  // 上期所交易行情菜单切换
  shfeMenuClick(e){
    let current = e.currentTarget.dataset.current;
    let currentItem = this.data.shfeTableData.filter(i=>i.metalType == current);
    let _title = currentItem.length > 0 ? util.formatDate(currentItem[0].tradeDate, 'M月D日') + ' 上期所期货交易行情' : '上期所期货交易行情';
    let _array = currentItem.length > 0 ? currentItem[0].list : [];

    this.setData({
      ['tableInfo.data']: _array,
      title: _title,
      unit: '',
      currentShfeNav: current,
    })
  },
  // 日期选择变化
  bindDateChange: function(e) {
    this.setData({
      tradeDate: e.detail.value
    })
    if (Number(this.data.currentNav) == 0) {
      let _title = util.formatDate(e.detail.value, 'M月D日') + " LME基本金属官方开盘库存报告";
      this.setData({
        unit: "单位：吨",
        title: _title
      })
      this.getLmeStockFrontList()
    } else if (Number(this.data.currentNav) == 1) {
      let _title = util.formatDate(e.detail.value, 'M月D日') + " LME基本金属注销仓单";
      this.setData({
        unit: "单位：吨",
        title: _title
      })
      this.getLmeWarehouseFrontList()
    } else if (Number(this.data.currentNav) == 2) {
      let _title = util.formatDate(e.detail.value, 'M月D日') + " COMEX铜库存统计";
      this.setData({
        unit: "单位：短吨",
        title: _title
      })
      this.getComexFrontList()
    } else if (Number(this.data.currentNav) == 3) {
      let _title = util.formatDate(e.detail.value, 'M月D日') + " 上期所仓单日报";
      this.setData({
        unit: "单位：吨",
        title: _title
      })
      this.getShfeWarehouseFrontList()
    } else if (Number(this.data.currentNav) == 4) {
      let _title = util.formatDate(e.detail.value, 'M月D日') + " 上期所库存周报";
      this.setData({
        unit: "单位：吨",
        title: _title
      })
      this.getShfeStockFrontList()
    } else if (Number(this.data.currentNav) == 5) {
      let _title = util.formatDate(e.detail.value, 'M月D日') + " 上期所期货交易行情";
      this.setData({
        unit: "",
        title: _title
      })
      this.getShfeFuturesQuotesList()
    }
  },

  onShareAppMessage() {
    return {
      title: "数据",
      path: "/packageA/pages/data/index?currentNav="+this.data.currentNav+"&currentShfeNav="+this.data.currentShfeNav+"&tradeDate="+this.data.tradeDate+"&isShare=true",
    }
  },

  onShareTimeline() {
    return {
      title: "数据",
      query: "currentNav="+this.data.currentNav+"&currentShfeNav="+this.data.currentShfeNav+"&tradeDate="+this.data.tradeDate+"&isShare=true"
    }
  }
})